<template>
<view class="body">
	<view class="header">
		<scroll-view scroll-y="true" @scroll="sceollTop" class="history" :scroll-into-view="toView">
			<block v-for="(item,index) in list" :key="index" class="content">
				<view class='my_right' v-if="item.uid == uid" :id='"AM"+index'>
					<text class="time" v-if="item.addtime">{{item.addtime}}</text>
					<view class='p_r'>
						<view class='new_txt' @longpress="longTime(index)">
							<view class='new_txt_my'>{{item.content}}
								<view class='new_txt_content'v-if="showArr[index]">
									<view @click="addWord(item.content,index)">添加常用语</view>
									<view @click="closeShow(index)">取    消</view>
								</view>
							</view>
						</view>
						<image v-if="uimg" class='new_img' :src='uimg'></image>
					</view>
				</view>
				<view class='you_left' v-if="item.uid == touid" :key="index" :id='"AM"+index'>
					<text class="time" v-if="item.addtime">{{item.addtime}}</text>
					<view class='p_r1'>
						<image class='new_img1' v-if="toimg" :src='toimg'></image>
						<view class='new_txt'>
							<view class='new_txt_my'>{{item.content}}</view>
						</view>
					</view>
				</view>
			</block>
		</scroll-view>
	</view>
	<view class="write">
		<view class="word_left" @click="wordsOpen">常用语</view>
		<input type="text" @input="bindKeyInput" :value='inputValue'
		confirm-type = 'send' cursor-spacing = '10' @confirm="search"/>
		<image @click="search" src="/static/send.png"></image>
	</view>
	<view class="words" v-if="wordShow">
		<view class="words_title">
		    <text>常用语</text>
		    <image class="word_close" @click="wordsClose" src='/static/img/none_close.png'></image>
		</view>
		<scroll-view class="scrollBotton" scroll-y="true" scroll-top="350rpx"
		scroll-with-animation="true">
			<view class="word_line" @click="wordsSend(item.remark)" v-for="(item,index) in words" :key="index">{{item.remark}}</view>
		</scroll-view>
		<view @click="gowords" class="words_bottom">管理常用语</view>
	</view>
</view>
</template>
<script>
import request from '@/util/request.js'
export default {
	data() {
		return {
			scrollHeight:'100vh',
			height3: '',
			toView:'',
			list:[],
			wordShow:false,
			setInter:null,
			inputValue:'',
			words:[],
			toimg:'',
			showArr:[]
		}
	},
	onLoad:function(e) {
		var touid = e.touid
		this.touid = touid
		this.socketInit()
	},
	onUnload: function() {
		//console.log('释放')
		var that = this
		//console.log(this.setInter)
		if(this.setInter) {
			clearInterval(this.setInter);  
			this.setInter = null;
			//console.log(this.setInter)
		}
	},
	onHide:function(){
		//console.log('释放22')
		var that = this
	    if(this.setInter) {
	    	clearInterval(this.setInter);  
	    	that.setInter = null;    
	    }
	},
	methods: {
		socketInit:function(){
			var that =this
			//判断是否否已连接
			uni.sendSocketMessage({
				data: 'ping',
				success: (res) => {
					console.log('一直在线',res)
					return;
				},
				fail: (err) => { // 未连接打开websocket连接
					that.openConnection();
				}
			});
		},
		openConnection:function(){
			var that = this
			// 创建一个 websocket 连接  ws://ip:端口号
			uni.connectSocket({				// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
				url: 'ws://47.94.242.46:9501',
				success(data) {
					console.log("websocket正在连接...",data);
				},
			});
			//  连接建立时触发
			uni.onSocketOpen(function (res) {
				 console.log('WebSocket连接成功',res);
			});
			// //监听socket错误
			uni.onSocketError(function (res) {
			  console.log('WebSocket连接打开失败，请检查！');
			});	
			// //监听socket关闭
			uni.onSocketClose(()=>{
				console.log('WebSocket连接已关闭！');
			})
			//监听socket消息
			uni.onSocketMessage(function (res) {
				let backMsg = res.data;
				that.backData(JSON.parse(backMsg));
			});
		},
		backData:function(data){
			console.log('返回数据',data);
			return false;
			switch (data) {
				case 'handShake':
					//首次登录，发送登陆数据
					var user_info = {'type': 'login', 'msg': uname, 'headerimg': headerimg};
					sendMsg(user_info);
					break;
				case 'login':
					userList(data.user_list);
					systemMessage('系统消息: ' + data.msg + ' 已上线');
					break;
				case 'logout':
					userList(data.user_list);
					if (data.msg.length > 0) {
						systemMessage('系统消息: ' + data.msg + ' 已下线');
					}
					break;
				case 'user':
					messageList(data);
					break;
				case 'system':
					systemMessage();
					break;
			}
		},
		onSocketMessage:function(type = 1){
			this.timeout = 60000;
			this.timeoutObj = null;
			uni.onSocketMessage((res) => {
				let backMsg = res.data;
				console.log('返回数据',JSON.parse(backMsg));
				// 后台绑定client_id
				// 如果返回有数据 转换
				// if (backMsg) {
				// 	let msg = JSON.parse(backMsg);
				// 	console.log('返回数据',msg);
					
				// 	if (msg.type ===  'init' || type === 2) {
				// 		console.log("判断是否有数据"+backMsg)
				// 		let clientId =  msg.client_id;
				// 		let userId = uni.getStorageSync('userInfo');
				// 		let para = {client_id: clientId, userId : userId  };
				// 		console.log("触发心跳")
				// 		this.reset(); 
				
				// 	}
				//}
				// 如果没连接成功服务器并没有返回数据
				//this.getSocketMsg(res.data); // 监听到有新服务器消息
			})
		},
		getList:function(){
		    var that = this
		    var data = {
				'uid':uni.getStorageSync('uid'),
				'touid':this.touid,
			}
			request({
				url: 'online/list',
				method: 'get',
				data:data,
				success: (res) => {
					if(res.data.code == 1){
						var str = res.data.data.length - 1;
						that.list = res.data.data
						that.$nextTick(()=> {
							that.toView = 'AM' + str
						});
						//that.toView = 'AM'+ str
						//console.log('开始',that.toView)
					}
				}
			})
		},
		getInfo:function(){
			var that = this
			var data = {'uid':this.touid}
			request({
				url: 'member/status',
				method: 'get',
				data:data,
				success: (res) => {
					if(res.data.code == 1){
						that.toimg = res.data.data.avatar
					}
				},
			})
		},
		wordsOpen:function(){
			var that = this
			var data = {uid:uni.getStorageSync('uid')}
			request({
				url: 'problem/words',
				method: 'get',
				data:data,
				success: (res) => {
					if(res.data.code == 1){
						that.wordShow = true
						that.words = res.data.data
					}
				}
			})
		},
		wordsSend:function(item){
			this.inputValue = item
			this.wordShow = false
			this.send()
		},
		send:function(){
		    if(!this.inputValue){
		      return;
		    } 
			uni.sendSocketMessage({
				data:'type=only&uid=2&touid=3',
				success(res) {
					console.log(res);
					console.log("消息发送成功");
				}
			});
			// let content = this.replaceEmoji(this.textMsg);
			// let msg = {text:content}
			// this.sendMsg(msg,'text');
			// this.textMsg = '';//清空输入框
			// var data = {
			// 	uid:uni.getStorageSync('uid'),
			// 	touid:this.touid,
			// 	content:this.inputValue,
			// }
			// uni.sendSocketMessage({
			// 	data:JSON.stringify(data),
			// 	success: (res) => {
			// 		console.log('发送成功',res)
			// 	},
			// 	fail:(err) => {
			// 		console.log(err)
			// 	}
			// })
			return;
		    var that = this
		    var data = {
				'uid':uni.getStorageSync('uid'),
				'touid':this.touid,
				'content':this.inputValue,
			}
		    var list = that.list
			request({
				url: 'online/add',
				method: 'post',
				data:data,
				success: (res) => {
					that.inputValue = '',
					that.list = list.concat(data)
				}
			})
		},
		bindKeyInput:function(e){
			this.inputValue = e.detail.value
		},
		search:function(){
			this.send()
		},
		sceollTop:function(e){
			var that = this
		    var type = e.detail.deltaY
		    if(type > 0){//上滑动
				//console.log('上划释放')
				if(this.setInter) {
					clearInterval(that.setInter);  
					that.setInter = null;  
				}
		    }else{//下滑动
				if(!this.setInter){
					that.setInter = setInterval(function(){
						//console.log('下划执行')
					    that.getList();
					},2000)
				}
			}
		 },
		 gowords:function(){
		 	uni.navigateTo({
		 		url:'/pages/message/online/words'
		 	});
		 },
		 wordsClose:function(){
			 this.wordShow = false
		},
		longTime:function(index){
			this.showArr[index] = true
			this.$forceUpdate();
		},
		closeShow:function(index){
			this.showArr[index] = false
			this.$forceUpdate();
		},
		addWord:function(content,index){
			var data = {
				uid:uni.getStorageSync('uid'),
				remark:content
			}
			var that = this
			request({
				url: 'problem/wordsAdd',
				method: 'post',
				data:data,
				success: (res) => {
					that.showArr[index] = false
					that.$forceUpdate();
				}
			})
		}
	}
}
</script>
<style scoped>
	@import url("./online/css/toCompany.css");
</style>